package com.leilei.controller;

import com.leilei.entity.Commodity;
import com.leilei.entity.Page;
import com.leilei.service.ICommodityService;
import com.leilei.service.impl.CommodityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/CommodityManagerServlet")
public class CommodityManagerServlet extends BaseServlet{

    private ICommodityService commodityService = new CommodityServiceImpl();
    private static final int pageSize = 5;

    public CommodityManagerServlet(){

    }


    protected void getCommodityByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String scurrentPage = req.getParameter("currentPage");
        int currentPage = scurrentPage == null ? 1 : Integer.parseInt(scurrentPage);

        req.setAttribute("currentPage", currentPage);

        Page p = new Page(currentPage, pageSize);

        int type = Integer.parseInt(req.getParameter("type"));

        int count = commodityService.getCountByType(type);

        p.setMaxPage(count % pageSize == 0 ? count / pageSize : (count / pageSize + 1));

        List<Commodity> list = commodityService.getCommodityByPage(p, type);
        req.setAttribute("list", list);
        req.setAttribute("maxPage", p.getMaxPage());
        req.setAttribute("type", type);

        req.getRequestDispatcher("/jsp/manager.jsp").forward(req, resp);

    }


}
